<?php

namespace App\Http\Controllers\Admin\Traits;

use App\Org\Dns;
use Illuminate\Support\Facades\Redis;
use Validator,Saas,DB,Log,Auth;
use App\Org\RandomOrderNumber;

trait AdminTrait{
    public static $config = [
        // 广告管理
        'advertisment' => [
            [
                'val' => 1,
                'name' => 'PC端',
                'children' => [[
                    'val' => 1,
                    'name' => '登录页']
                ]
            ],
            [
                'val' => 2,
                'name' => 'wap商城',
                'children' => [[
                    'val' => 1,
                    'name' => '首页banner']
                ]
            ]
        ]
    ];

    /**
     * 返回Appsecret
     * @return string
     */
    protected function return_appsecret()
    {
        return 'Y61zjrG6c4HgzowP';
    }

    /**
     * @desc 检测域名是否已经解析
     * @param $domain 域名
     * @return boolean
     */
    protected function domainIsExists($domain)
    {
        if (empty($domain)) {
            return false;
        }

        $mainDomain = explode('.', $domain);
        $data_send  = [
            'PageNumber' => 1,
            'PageSize'   => 10,
        ];

        $data_send['RRKeyWord'] = '';
        foreach ($mainDomain as $val) {
            if ($val == 'cadj')
                break;
            $data_send['RRKeyWord'] .= $val . '.';
        }
        $data_send['RRKeyWord'] = rtrim($data_send['RRKeyWord'], '.');

        $res = Dns::getDomainRecords($data_send);
        if (empty($res))
            return false;

        if (isset($res['count'])) {
            if (!$res['count']) return false;

            foreach ($res['list'] as $value) {
                if ($data_send['RRKeyWord'] == $value->RR) return true;
                break;
            }
        }

        return false;
    }

    /**
     * 校验签名
     * @param $arr
     * @param $sign
     * @return bool
     */
    protected function check_sign($arr, $sign)
    {
        if(isset($arr['active'])){
            unset($arr['active']);
        }
        ksort($arr);
        $str = '';
        foreach ($arr as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $new_sign = md5(mb_substr($str, 0, -1) . $this->return_appsecret());

        if ($new_sign == $sign) {

            return true;
        } else {

            return false;
        }
    }

    protected  function  sendCurl($url)
    {
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     *
     * @return 返回已经拼接好的字符串
     */
    protected function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    protected function str_rand($length = 12, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    {
        if(!is_int($length) || $length < 0) {
            return false;
        }
        $string = '';
        for($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }
        return $string;
    }

    /**
     * 处理查询条件
     * @return object
     */
    protected function search($request){
        return $this->model;
    }


    /**
     * 列表处理
     * @return \stdClass
     */
    protected function _list($request)
    {
        $select = $this->search($request);

        //处理排序
        if(isset($this->orderBy)){
            foreach ($this->orderBy as $k=>$v){
                $select = $select->orderBy($k,$v);
            }
        }else{
            $select = $select->orderBy('id','desc');
        }

        $per_page = $request->per_page ? $request->per_page : 20;
        $list = $select->paginate($per_page);

        if (method_exists($this, 'transformList'))
        {
            $list=$this->transformList($list);
        }
        $list->appends($request->all());
        return $list;
    }
    /**
     * 生成相对唯一单号
     * @param $prefix //单号前缀
     * @return string
     */
    protected function sn($prefix){
        try{
            if (config('pin_setting.order_number_generation_rule')){
                $snowflake = new RandomOrderNumber(1,$prefix);
                return $snowflake->next();
            }else{
                $key = $prefix.Auth::user()->company_id;
                if (!Redis::exists($key)){
                    $end_time = strtotime('23:59:59')-time();
                    Redis::setex($key, $end_time, 0);
                }
                return $prefix.date('Ymd').sprintf("%04d",Redis::incr($key));
            }
        }catch(Exception $e){
            //echo 'Message: ' .$e->getMessage();
            return $prefix.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        }
    }

    /**
     * 处理表单验证
     * @return string or bool
     */
    protected function validate_form($request){
        $rule = $this->validate_rule;
        if (method_exists($this, 'rules')) {
            $rule = $rule+$this->rules();
        }
        $validator = Validator::make($request->all(),$rule,$this->err_msg);

        if ($validator->fails()) {
            //失败返回信息
            return $validator->errors()->first();
        }else{
            return true;
        }
    }

    protected function success($data=[])
    {
        if(is_null($data))
        {
            $data=new \stdClass();
        }
        return response()->json(['errcode'=>0,'errmsg'=>'ok','data'=>$data]);
    }

    protected function error($err=['-1','系统错误',[]])
    {
        $err_data=isset($err[2])?$err[2]:[];
        return response()->json(['errcode'=>$err[0],'errmsg'=>$err[1],'data'=>$err_data]);
    }

    public function Sec2Time($time){
        if(is_numeric($time)){
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            if($time >= 31556926){
                $value["years"] = floor($time/31556926);
                $time = ($time%31556926);
            }
            if($time >= 86400){
                $value["days"] = floor($time/86400);
                $time = ($time%86400);
            }
            if($time >= 3600){
                $value["hours"] = floor($time/3600);
                $time = ($time%3600);
            }
            if($time >= 60){
                $value["minutes"] = floor($time/60);
                $time = ($time%60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;
            $t=$value["years"] ."年". $value["days"] ."天"." ". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
            Return $t;

        }else{
            return (bool) FALSE;
        }
    }

    public static function Sec2TimeStatic($time)
    {
        if(is_numeric($time)){
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            if($time >= 31556926){
                $value["years"] = floor($time/31556926);
                $time = ($time%31556926);
            }
            if($time >= 86400){
                $value["days"] = floor($time/86400);
                $time = ($time%86400);
            }
            if($time >= 3600){
                $value["hours"] = floor($time/3600);
                $time = ($time%3600);
            }
            if($time >= 60){
                $value["minutes"] = floor($time/60);
                $time = ($time%60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;
            $t=$value["years"] ."年". $value["days"] ."天"." ". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
            Return $t;

        }else{
            return (bool) FALSE;
        }
    }

    public function getImgPrefix()
    {
        $domain=config('filesystems.disks.oss.cdnDomain');
        $http=config('filesystems.disks.oss.ssl')?'https://':'http://';
        $prefix= $http.$domain.'/';
        return $prefix;
    }

    public function sn_job($prefix){
        try{
            $key = $prefix;
            if (!Redis::exists($key)){
                $end_time = strtotime('23:59:59')-time();
                Redis::setex($key, $end_time, 0);
            }
            return $prefix.date('Ymd').sprintf("%04d",Redis::incr($key));
        }catch(\Exception $e){
            return $prefix.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        }
    }

    public function getHttpHost()
    {
        $proto = empty($_SERVER['HTTP_X_CLIENT_PROTO']) ? 'http://' : $_SERVER['HTTP_X_CLIENT_PROTO'] . '://';
        return $proto.$_SERVER['HTTP_HOST'];
    }

}
